

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言预编译和作用域链，本质上是让我们对作用域有一个更深层次的认知。 而不是只停留在，全局作用域和局部作用域的区别。 然而javascript的作用域，因为预编译的存在，会变得和其他语言很有大的不同。 有时候，你觉得视觉和代码逻辑上不应该发生的问题，拿到javascript中，又变得十分合理。 作用域作用域总体会分成两个大类  全局作用域，代码任何一个地方都可以调用 局部作用域，只有在特定的区域可以">
<meta property="og:type" content="article">
<meta property="og:title" content="预编译与作用域链">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/09/28/notes/js/precompile/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言预编译和作用域链，本质上是让我们对作用域有一个更深层次的认知。 而不是只停留在，全局作用域和局部作用域的区别。 然而javascript的作用域，因为预编译的存在，会变得和其他语言很有大的不同。 有时候，你觉得视觉和代码逻辑上不应该发生的问题，拿到javascript中，又变得十分合理。 作用域作用域总体会分成两个大类  全局作用域，代码任何一个地方都可以调用 局部作用域，只有在特定的区域可以">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-09-28T12:05:25.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.258Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="测试平台">
<meta property="article:tag" content="javascript">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>预编译与作用域链 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="预编译与作用域链"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-09-28 20:05" pubdate>
          2022年9月28日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.2k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">预编译与作用域链</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>预编译和作用域链，本质上是让我们对<strong>作用域</strong>有一个更深层次的认知。</p>
<p>而不是只停留在，全局作用域和局部作用域的区别。</p>
<p>然而javascript的作用域，因为<strong>预编译</strong>的存在，会变得和其他语言很有大的不同。</p>
<p>有时候，你觉得视觉和代码逻辑上不应该发生的问题，拿到javascript中，又变得十分合理。</p>
<h1 id="作用域"><a href="#作用域" class="headerlink" title="作用域"></a>作用域</h1><p>作用域总体会分成两个大类</p>
<ul>
<li>全局作用域，代码任何一个地方都可以调用</li>
<li>局部作用域，只有在特定的区域可以调用</li>
</ul>
<p>局部作用域可以访问全局作用域，全局作用域在某种情况下也可以访问到局部作用域定义的变量。</p>
<h1 id="预编译"><a href="#预编译" class="headerlink" title="预编译"></a>预编译</h1><p>js的代码执行顺序，一共分为三步：</p>
<ul>
<li>语法分析，全局扫描，查看是否有语法错误</li>
<li>预编译</li>
<li>执行</li>
</ul>
<p>所以，预编译会发生在执行之前。</p>
<p>而这个预编译，就会造成一个不算是问题的问题：变量提升</p>
<h2 id="变量提升"><a href="#变量提升" class="headerlink" title="变量提升"></a>变量提升</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a); <span class="hljs-comment">// undefined</span><br><span class="hljs-keyword">var</span> a = <span class="hljs-number">1</span>;<br></code></pre></td></tr></table></figure>

<p>我们之前说过，undefined是什么意思？可以表示是已经定义了但是没有值的意思。</p>
<p>但是按照代码中的执行顺序来说，console.log执行在变量定义之前，那为什么还能调用这个变量？</p>
<p>所以，这就是预编译带来的问题。</p>
<p>再来看一个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-title function_">test</span>()<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>现在js对上面代码的现象会总结成两句话，也会有很多工程师靠着这两句话吃了很久。</p>
<p>但这两句话，远远不能解决预编译会产生的问题，也不能完全概括预编译的原理。</p>
<blockquote>
<ol>
<li>函数声明整体提升，将函数定义放在代码的最顶部。</li>
<li>变量声明提升，将变量声明到代码最顶部，但不包括赋值。</li>
</ol>
</blockquote>
<p>举个这两句话解决不了的例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(test);  <span class="hljs-comment">// function test</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params">test</span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(test); <span class="hljs-comment">// 1</span><br>    <span class="hljs-keyword">var</span> test = <span class="hljs-number">234</span><br><br>    <span class="hljs-keyword">var</span> test = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br><br>    &#125;<br><br>    <span class="hljs-title function_">test</span>()<br>&#125;<br><br><span class="hljs-title function_">test</span>(<span class="hljs-number">1</span>)<br><br><span class="hljs-keyword">var</span> test = <span class="hljs-number">123</span><br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(test);  <span class="hljs-comment">// 123</span><br></code></pre></td></tr></table></figure>

<p>在python里面，肯定就是第一步就报错了，因为test还没有被定义。但是js中就允许它的存在，而且没学习预编译之前，你还很难去确定每个test的值。</p>
<h2 id="预编译原理"><a href="#预编译原理" class="headerlink" title="预编译原理"></a>预编译原理</h2><h3 id="预编译铺垫"><a href="#预编译铺垫" class="headerlink" title="预编译铺垫"></a>预编译铺垫</h3><blockquote>
<ol>
<li>一个变量，不管在哪，只要没有经过显示声明而赋值，就可以当作全局变量来使用。</li>
<li>在全局作用域中，var a = 123 相当于 a = 123</li>
<li>在局部作用域中，显式声明就只能作用域局部作用域</li>
<li>一切全局变量，都相当于是给window对象声明一个属性 a = 123 相当于 window.a = 123</li>
<li>window代表的就是全局作用域</li>
</ol>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">123</span><br><br>b = <span class="hljs-number">123</span><br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">window</span>.<span class="hljs-property">a</span>) <span class="hljs-comment">// 123</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a) <span class="hljs-comment">// 123</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params"></span>)&#123;<br>    c = <span class="hljs-number">123</span><br>    <span class="hljs-keyword">var</span> d = <span class="hljs-number">123</span><br><br>    <span class="hljs-keyword">var</span> e = f = <span class="hljs-number">123</span><br>&#125;<br><br><span class="hljs-title function_">test</span>()<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c); <span class="hljs-comment">// 123</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(f); <span class="hljs-comment">// 123</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(d);  <span class="hljs-comment">// error</span><br></code></pre></td></tr></table></figure>

<h3 id="预编译过程"><a href="#预编译过程" class="headerlink" title="预编译过程"></a>预编译过程</h3><p>预编译发生在函数执行的前一刻</p>
<p>下面我们先用函数的预编译过程来进行讲解</p>
<p>然后再进行全局的预编译讲解</p>
<p>这个过程一共历经四步：</p>
<ul>
<li>创建AO（Activation Object）对象，也叫做<strong>执行上下文</strong></li>
<li>寻找形参和变量声明，如果有形参或者变量声明，则将其作为AO对象的属性值, 值为undefined</li>
<li>如果有形参，将传入的实参赋值给AO对象中对应形参的属性</li>
<li>寻找函数声明，将函数体赋值给AO对象中的属性。无则新增，有则覆盖</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params">test</span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(test); <span class="hljs-comment">// function test&#123;&#125;</span><br><br>    <span class="hljs-keyword">var</span> test = <span class="hljs-number">123</span><br><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(test);  <span class="hljs-comment">// 123</span><br><br>    <span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params"></span>)&#123;<br><br>    &#125;<br>&#125;<br><span class="hljs-title function_">test</span>(<span class="hljs-number">1</span>)<br><br><span class="hljs-comment">// 第一步，创建AO对象&#123;&#125;</span><br><span class="hljs-comment">// 第二步 查找形参和变量声明，所以这个时候AO为 &#123;test: undefined&#125;</span><br><span class="hljs-comment">// 第三步，将实参赋值给AO属性，&#123;test: 1&#125;</span><br><span class="hljs-comment">// 第四步，查看是否有函数声明，如果有，赋值给AO对象&#123;test: function test&#123;&#125;&#125;</span><br><br><span class="hljs-comment">// 函数开始执行</span><br><span class="hljs-comment">// 所以第一行的test为function test&#123;&#125;</span><br><span class="hljs-comment">// 第二次的test为123，因为执行了var test = 123</span><br><span class="hljs-comment">// 最后的test函数声明，因为在预编译时已经获取到了，所以不管它了</span><br></code></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params">c</span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c);  <span class="hljs-comment">// 1</span><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a); <span class="hljs-comment">// function a</span><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b);  <span class="hljs-comment">// undefined</span><br><br>    <span class="hljs-keyword">var</span> a = <span class="hljs-number">123</span><br><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a);  <span class="hljs-comment">// 123</span><br><br>    <span class="hljs-keyword">function</span> <span class="hljs-title function_">a</span>(<span class="hljs-params"></span>)&#123;&#125;<br><br>    <span class="hljs-keyword">var</span> b = <span class="hljs-number">234</span><br>    <br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b);  <span class="hljs-comment">// 234</span><br>&#125;<br><span class="hljs-title function_">test</span>(<span class="hljs-number">1</span>)<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">第一步，创建AO对象</span><br><span class="hljs-comment">第二步，寻找形参和变量声明 &#123;</span><br><span class="hljs-comment">    c: undefined,</span><br><span class="hljs-comment">    a: undefined.</span><br><span class="hljs-comment">    b: undefined</span><br><span class="hljs-comment">&#125;</span><br><span class="hljs-comment">第三步，实参赋值，&#123;</span><br><span class="hljs-comment">    c: 1,</span><br><span class="hljs-comment">    a: undefined,</span><br><span class="hljs-comment">    b: undefined</span><br><span class="hljs-comment">&#125;</span><br><span class="hljs-comment">第四步，寻找函数声明，&#123;</span><br><span class="hljs-comment">    c: 1,</span><br><span class="hljs-comment">    a: function a</span><br><span class="hljs-comment">    b: undefined</span><br><span class="hljs-comment">&#125;</span><br><span class="hljs-comment">*/</span><br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">函数开始执行</span><br><span class="hljs-comment">开始的log c a b会直接从AO对象中取值</span><br><span class="hljs-comment"></span><br><span class="hljs-comment">执行到对应的变量赋值时，将AO对象中的值进行覆盖</span><br><span class="hljs-comment"></span><br><span class="hljs-comment">*/</span><br></code></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b); <span class="hljs-comment">// undefined</span><br>    <span class="hljs-keyword">if</span>(a)&#123;<br>        <span class="hljs-keyword">var</span> b = <span class="hljs-number">123</span><br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">var</span> a<br><br><span class="hljs-title function_">test</span>()<br><br></code></pre></td></tr></table></figure>

<h3 id="全局预编译"><a href="#全局预编译" class="headerlink" title="全局预编译"></a>全局预编译</h3><p>相对于函数预编译，它只有三个步骤：</p>
<ul>
<li>创建GO（Global Object）对象, window对象就是GO</li>
<li>寻找变量声明，如果有，就在GO中创建属性，值为undefined</li>
<li>寻找函数声明，如果有，就在GO中进行属性的赋值，无则新增，有则覆盖</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(test); <span class="hljs-comment">// function test</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(test1);  <span class="hljs-comment">// undefined</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params"></span>)&#123;<br><br>&#125;<br><br><span class="hljs-keyword">var</span> test1 = <span class="hljs-number">123</span><br></code></pre></td></tr></table></figure>

<h1 id="作用域链"><a href="#作用域链" class="headerlink" title="作用域链"></a>作用域链</h1><p>作用域链决定变量的调用顺序</p>
<p>可以总结为：</p>
<ul>
<li>局部作用域中，优先查找自己的AO</li>
<li>如果AO中没有对应属性，则查找上一层AO</li>
<li>如果没有上一层，则查找全局GO</li>
<li>如果GO没有，再报错</li>
</ul>
<h2 id="scope"><a href="#scope" class="headerlink" title="scope"></a>scope</h2><p>每个函数，都可以理解成一个对象</p>
<p>每个函数都有些属性我们可以访问，有些我们不可以访问</p>
<p>不可访问的属性，只能被js执行引擎使用。</p>
<p>scope就是作用域，其中存储了我们的<strong>执行上下文</strong>，也就是我们说的GO、AO。</p>
<p>它是以链式存储的，也就是说，调用顺序有先后，这就是<strong>作用域链</strong></p>
<h2 id="执行上下文"><a href="#执行上下文" class="headerlink" title="执行上下文"></a>执行上下文</h2><p>每当函数执行时，都会创建一个<strong>独一无二</strong>的执行上下文，并且在函数执行结束时销毁。</p>
<blockquote>
<p>销毁，实际上是去掉自己对之前创建的AO对象的引用。这其实也和 内存管理 中的 引用 有关<br>一旦销毁了对作用域的引用，那么该作用域就会被内容管理机制给销毁掉。<br>这里提一嘴，为什么闭包会造成内存泄漏，就是因为 引用 的作用域一直存在。垃圾回收机制中有 引用计数，一旦有引用，就不会被回收。</p>
</blockquote>
<p>多次执行函数， 会创建多个执行上下文。</p>
<p>执行上下文决定着函数的运行环境，也就是可供调用的变量属性。</p>
<p>而变量的查找，就根据作用域链的排序进行查找。</p>
<p>比如：</p>
<p>0: AO<br>1: GO</p>
<p>函数创建的AO，会直接放在scope的第一位，其他的scope成员依次往后排。这个动作发生在<strong>预编译</strong></p>
<h2 id="GO对象"><a href="#GO对象" class="headerlink" title="GO对象"></a>GO对象</h2><p>GO会存放：</p>
<ul>
<li>this</li>
<li>window</li>
<li>document</li>
<li>其他属性</li>
</ul>
<h2 id="AO"><a href="#AO" class="headerlink" title="AO"></a>AO</h2><p>AO会存放：</p>
<ul>
<li>this</li>
<li>arguments</li>
<li>其他属性</li>
</ul>
<h2 id="作用域链继承"><a href="#作用域链继承" class="headerlink" title="作用域链继承"></a>作用域链继承</h2><p>函数内创建的函数，会继承外函数的scope</p>
<h2 id="实践解读"><a href="#实践解读" class="headerlink" title="实践解读"></a>实践解读</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">a</span>(<span class="hljs-params"></span>)&#123;<br>&#125;<br><br><span class="hljs-title function_">a</span>()<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">第一步，函数a被定义，但没有执行。a.[[scope]] -&gt; 0: GO</span><br><span class="hljs-comment">第二步，函数a被执行，这时候触发预编译。a.[[scope]] -&gt; 0: AO  1: GO</span><br><span class="hljs-comment">*/</span><br></code></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">a</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-keyword">function</span> <span class="hljs-title function_">b</span>(<span class="hljs-params"></span>)&#123;<br><br>    &#125;<br>    <span class="hljs-title function_">b</span>()<br>&#125;<br><span class="hljs-title function_">a</span>()<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">第一步，函数a被定义，但没有执行。a.[[scope]] -&gt; 0: GO</span><br><span class="hljs-comment">第二步，函数a被执行，这时候触发a的预编译。a.[[scope]] -&gt; 0: aAO 1: GO</span><br><span class="hljs-comment">第三步，函数b被定义，这个时候继承a的scope环境。b.[[scope]] -&gt; 0: aAO 1: GO</span><br><span class="hljs-comment">第四步，函数b被执行，这个时候出发b的预编译。b.[[scope]] -&gt; 0: bAO 1: aAO 2: GO</span><br><span class="hljs-comment">*/</span><br></code></pre></td></tr></table></figure>

<p>由于scope的存在，查找变量变得有序，按照作用域链依次查找。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> g = <span class="hljs-number">123</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(g); <span class="hljs-comment">// undefined</span><br>    <span class="hljs-keyword">var</span> g = <span class="hljs-number">234</span><br>&#125;<br><span class="hljs-title function_">test</span>()<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">第一步，全局GO &#123;g: 123&#125;</span><br><span class="hljs-comment">第二步，定义函数test</span><br><span class="hljs-comment">第三步，执行test，触发预编译。这个时候AO: &#123;g: undefined&#125;</span><br><span class="hljs-comment">第四步，执行打印g，获取AO的g属性undefined</span><br><span class="hljs-comment">*/</span><br></code></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">test</span>(<span class="hljs-params"></span>)&#123;<br>    <span class="hljs-keyword">var</span> a = <span class="hljs-number">123</span><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a);<br>    <span class="hljs-keyword">function</span> <span class="hljs-title function_">test1</span>(<span class="hljs-params"></span>)&#123;<br>        a = <span class="hljs-number">234</span><br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a);<br>    &#125;<br>    <span class="hljs-title function_">test1</span>()<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a);<br>&#125;<br><span class="hljs-title function_">test</span>()<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">由于继承，在test1中可以直接修改由test继承过来的a属性</span><br><span class="hljs-comment">*/</span><br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/" class="category-chain-item">测试开发</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/javascript/" class="category-chain-item">javascript</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%B9%B3%E5%8F%B0/">#测试平台</a>
      
        <a href="/my-blog/tags/javascript/">#javascript</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>预编译与作用域链</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/09/28/notes/js/precompile/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年9月28日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/09/29/notes/js/closure/" title="闭包精讲">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">闭包精讲</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/09/26/notes/js/commonFunction/" title="javascript常用函数">
                        <span class="hidden-mobile">javascript常用函数</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
